package com.zoffy.wmsbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoffy.wmsbackend.common.ErrorCode;
import com.zoffy.wmsbackend.mapper.TransferOrderMapper;
import com.zoffy.wmsbackend.mapper.WarehouseMapper;
import com.zoffy.wmsbackend.model.dto.transfer.TransferDetailDTO;
import com.zoffy.wmsbackend.model.dto.transfer.TransferOrderDto;
import com.zoffy.wmsbackend.model.dto.transfer.TransferDTO;
import com.zoffy.wmsbackend.model.entity.*;
import com.zoffy.wmsbackend.model.vo.materialUsagePlan.MaterialUsagePlanDetailVo;
import com.zoffy.wmsbackend.model.vo.materialUsagePlan.MaterialUsagePlanDetailsVo;
import com.zoffy.wmsbackend.model.vo.transfer.TransferDetailVo;
import com.zoffy.wmsbackend.model.vo.transfer.TransferOrderDetailsVo;
import com.zoffy.wmsbackend.model.vo.transfer.TransferOrderVo;
import com.zoffy.wmsbackend.service.GoodsService;
import com.zoffy.wmsbackend.service.MaterialUsagePlanService;
import com.zoffy.wmsbackend.service.TransferOrderDetailService;
import com.zoffy.wmsbackend.service.TransferOrderService;
import com.zoffy.wmsbackend.utils.StockUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.util.UUID;
import java.util.stream.Collectors;
import com.zoffy.wmsbackend.exception.BusinessException;

@Service
public class TransferOrderServiceImpl  extends ServiceImpl<TransferOrderMapper, StockTransferOrder> implements TransferOrderService {

    @Resource
    private TransferOrderMapper transferOrderMapper;
    @Resource
    private GoodsService goodsService;
    @Resource
    private WarehouseMapper warehouseMapper;
    @Resource
    private TransferOrderDetailService transferOrderDetailService;
    @Resource
    private StockUtil stockUtil;

    @Resource
    private MaterialUsagePlanService materialUsagePlanService;

    @Override
    public Boolean importTransfer(MultipartFile file) throws IOException {
        // 这里需要实现具体的文件导入逻辑，例如解析文件内容并保存到数据库
        // 示例中简单返回 true 表示导入成功
        return true;
    }

    @Override
    public Boolean transfer(TransferDTO transferDto) {
        // 仿照 StockInOrderServiceImpl.java 中的逻辑
        // 获取商品信息
        Map<String, Goods> goodsMap = goodsService.list().stream().collect(Collectors.toMap(Goods::getGoodsCode, k -> k));
        List<StockTransferOrderDetail> transferOrderDetails = new ArrayList<>();
        String transferNo = transferDto.getStockTransferNo();
        List<TransferDetailDTO> transferDetails = transferDto.getTransferDetails();

        // 获取源仓库信息
        String originWarehouseCode = transferDto.getOriginWarehouseCode();
        LambdaQueryWrapper<Warehouse> originQueryWrapper = Wrappers.lambdaQuery();
        originQueryWrapper.eq(Warehouse::getWarehouseCode, originWarehouseCode);
        Warehouse originWarehouse = warehouseMapper.selectOne(originQueryWrapper);
        if (originWarehouse == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "源仓库不存在");
        }

        // 获取目标仓库信息
        String targetWarehouseCode = transferDto.getTargetWarehouseCode();
        LambdaQueryWrapper<Warehouse> targetQueryWrapper = Wrappers.lambdaQuery();
        targetQueryWrapper.eq(Warehouse::getWarehouseCode, targetWarehouseCode);
        Warehouse targetWarehouse = warehouseMapper.selectOne(targetQueryWrapper);
        if (targetWarehouse == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "目标仓库不存在");
        }

        // 创建 StockTransferOrder 实体对象
        StockTransferOrder stockTransferOrder = new StockTransferOrder();
        stockTransferOrder.setStockTransferNo(transferNo);
        stockTransferOrder.setOriginWarehouseId(originWarehouse.getId());
        stockTransferOrder.setTargetWarehouseId(targetWarehouse.getId());
        stockTransferOrder.setStatus((short) 0); // 假设 0 表示新建状态
        this.save(stockTransferOrder);

        // 处理调拨详情
        if(transferDetails!=null && !transferDetails.isEmpty()){
            transferDetails.forEach(transferDetail -> {
                String goodsNo = transferDetail.getGoodsNo();
                Integer num = transferDetail.getNum();
                Goods goods = goodsMap.get(goodsNo);
                StockTransferOrderDetail transferOrderDetail = new StockTransferOrderDetail();
                transferOrderDetail.setStockTransferOrderId(stockTransferOrder.getId());
                transferOrderDetail.setStockTransferDetailNo(transferDetail.getStockOutDetailNo());
                transferOrderDetail.setWarehouseId(originWarehouse.getId());
                transferOrderDetail.setGoodsId(goods.getId());
                transferOrderDetail.setQuantity(num);
                transferOrderDetail.setStatus((short) 0); // 假设 0 表示新建状态
                transferOrderDetails.add(transferOrderDetail);
            });

            // 批量保存调拨详情
            transferOrderDetailService.saveBatch(transferOrderDetails);
        }

        return true;
    }

    @Override
    public Page<TransferOrderVo> listTransferOrderVoByPage(com.zoffy.wmsbackend.common.RequestParam<TransferOrderDto> requestParam) {
        Long pageSize = requestParam.getPageSize();
        Integer pageNum = requestParam.getPageNum();
        TransferOrderDto dto = requestParam.getParams();
        Page<TransferOrderVo> page = new Page<>(pageNum, pageSize);
        Page<TransferOrderVo> res = transferOrderMapper.listTransferOrderVoByPage(page, dto);
        return res;
    }

    @Override
    public boolean approval(Long id) {
        // 获取调拨单信息
        StockTransferOrder transferOrder = this.getById(id);
        if (transferOrder == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "调拨单不存在");
        }
        transferOrder.setStatus((short) 90);
        // 更新调拨单信息
        this.updateById(transferOrder);

        // 查询该调拨单的所有详情
        LambdaQueryWrapper<StockTransferOrderDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StockTransferOrderDetail::getStockTransferOrderId, id);
        List<StockTransferOrderDetail> transferOrderDetails = transferOrderDetailService.list(queryWrapper);

        // 处理库存相关逻辑
        stockUtil.transferStock(transferOrder, transferOrderDetails);

        return true;
    }

    @Override
    public TransferOrderDetailsVo getDetailsById(Long id) {
        TransferOrderVo transferVo = transferOrderMapper.getTransferVoById(id);
        TransferOrderDetailsVo transferOrderDetailsVo = new TransferOrderDetailsVo();
        transferOrderDetailsVo.setTransferId(id);
        transferOrderDetailsVo.setOriginWarehouseCode(transferVo.getOriginWarehouseCode());
        transferOrderDetailsVo.setOriginWarehouseName(transferVo.getOriginWarehouseName());
        transferOrderDetailsVo.setTargetWarehouseCode(transferVo.getTargetWarehouseCode());
        transferOrderDetailsVo.setTargetWarehouseName(transferVo.getTargetWarehouseName());
        transferOrderDetailsVo.setTransferNo(transferVo.getTransferNo());
        // 调用 Mapper 方法获取调拨单的详细信息
        List<TransferDetailVo> details = transferOrderMapper.getDetailsById(id);
        transferOrderDetailsVo.setDetails(details);
        return transferOrderDetailsVo;
    }
    @Override
    @Transactional
    public Boolean generateTransferOrderByPlan(Long originWarehouseId, Long targetWarehouseId, Long materialUsagePlanId) {

        MaterialUsagePlan materialUsagePlan = materialUsagePlanService.getById(materialUsagePlanId);
        materialUsagePlan.setStatus(45);
        materialUsagePlanService.updateById(materialUsagePlan);

        // 获取用料计划详情
        MaterialUsagePlanDetailsVo planDetails = materialUsagePlanService.getDetailsById(materialUsagePlanId);
        if (planDetails == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用料计划不存在");
        }

        // 创建调拨单 DTO
        TransferDTO transferDto = new TransferDTO();
        transferDto.setStockTransferNo(UUID.randomUUID().toString()); // 生成唯一的调拨单号
        transferDto.setOriginWarehouseCode(getWarehouseCodeById(originWarehouseId));
        transferDto.setTargetWarehouseCode(getWarehouseCodeById(materialUsagePlan.getWarehouseId()));

        // 处理用料计划详情，转换为调拨详情
        List<TransferDetailDTO> transferDetails = new ArrayList<>();
        for (MaterialUsagePlanDetailVo detailVo : planDetails.getDetails()) {
            TransferDetailDTO transferDetail = new TransferDetailDTO();
            transferDetail.setStockOutDetailNo(UUID.randomUUID().toString()); // 生成唯一的调拨子单号
            transferDetail.setGoodsNo(detailVo.getGoodsCode());
            transferDetail.setNum(detailVo.getQuantity());
            transferDetails.add(transferDetail);
        }
        transferDto.setTransferDetails(transferDetails);

        // 调用已有的 transfer 方法创建调拨单
        return transfer(transferDto);
    }

    private String getWarehouseCodeById(Long warehouseId) {
        Warehouse warehouse = warehouseMapper.selectById(warehouseId);
        if (warehouse == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "仓库不存在");
        }
        return warehouse.getWarehouseCode();
    }
}